﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using AdminModule.IndexMarkServiceReference;

namespace AdminModule.AnswerLog.DataSource
{
    public sealed class GridTreeDataSource
    {
        public GridTreeDataSource(/*IList*/System.Collections.IEnumerable originalSource, Func<object, IList> getChildren)
        {
            List<object> tmp = new List<object>();
            foreach (object el in originalSource) tmp.Add(el);
            OriginalSource = tmp;
            GetChildren = getChildren;
            Source = new ObservableCollection<GridTreeDataItem>();

            FillWithGridTreeItems(Source, OriginalSource, 0);
        }


        public IList OriginalSource { get; private set; }

        private Func<object, IList> GetChildren { get; set; }

        public ObservableCollection<GridTreeDataItem> Source { get; private set; }

        private void FillWithGridTreeItems(IList<GridTreeDataItem> destinationCollection, IList sourceCollection, int level)
        {
            foreach (object item in sourceCollection)
            {
                GridTreeDataItem treeItem = new GridTreeDataItem(item, this, level);
                treeItem.IsVisible = (level == 0);
                destinationCollection.Add(treeItem);

                IList list = GetChildren(item);
                if (list != null)
                    FillWithGridTreeItems(treeItem.Children, list, level + 1);
            }
        }

        internal void NotifyIsExpandedChanged(GridTreeDataItem item)
        {
            if (item.IsVisible)
            {
                if (!item.IsExpanded)
                {
                    RemoveChildren(item);
                }
                else
                {
                    int index = Source.IndexOf(item);
                    AddChildren(item, ref index);
                }
            }
        }

        private void AddChildren(GridTreeDataItem element, ref int index)
        {
            foreach (var item in element.Children)
            {
                Source.Insert(++index, item);
                item.IsVisible = true;
                if (item.IsExpanded)
                {
                    AddChildren(item, ref index);
                }
            }
        }

        private void RemoveChildren(GridTreeDataItem element)
        {
            foreach (var item in element.Children)
            {
                Source.Remove(item);
                item.IsVisible = false;
                RemoveChildren(item);
            }
        }
    }
}
